package com.gy.bearhelps.news;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.gy.bearhelps.R;
import com.gy.bearhelps.base.BaseBean;
import com.gy.bearhelps.base.BaseFragment;
import com.gy.bearhelps.base.WebViewActivity;
import com.gy.bearhelps.news.adapter.NewsItemAdapter;
import com.gy.bearhelps.news.bean.NewsItemBean;
import com.gy.bearhelps.util.AnimUtil;
import com.gy.bearhelps.util.RequestResultListener;
import com.gy.bearhelps.util.Urls;
import com.gy.bearhelps.view.ChildViewPager;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 高岳 on 2016/11/2.
 * Describe:
 */
@SuppressLint("ValidFragment")
public class NewsItemFragment extends BaseFragment {

    private PullToRefreshListView refreshListView;
    private LinearLayout llEmpty;
    private NewsItemAdapter adapter;
    private List<NewsItemBean> mLists,requestLists;
    private View headerView;
    private ChildViewPager headerViewpager;
    private int channelId;
    private int pageStart = 0;
    private boolean isCreate;
    private String title;

    public NewsItemFragment(){

    }
    public NewsItemFragment(int channelId,String title){
        this.channelId = channelId;
        this.title = title;
    }

    @Override
    protected View setView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fg_news_item,null);
        hidenTop();
        return view;
    }

    @Override
    protected void initView() {
        refreshListView = (PullToRefreshListView) _rootView.findViewById(R.id.fg_news_lisview);
        headerView = View.inflate(mContext,R.layout.view_news_item_header,null);
        headerViewpager = (ChildViewPager) headerView.findViewById(R.id.view_news_header);
        llEmpty = (LinearLayout) _rootView.findViewById(R.id.fg_news_empty);
    }

    @Override
    protected void initData() {
        mLists = new ArrayList<>();
        requestLists = new ArrayList<>();
        adapter = new NewsItemAdapter(mContext,mLists);

    }

    @Override
    protected void setListener() {
        super.setListener();
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageStart = 0;
                showLoadDialog();
                getList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if(!isLoading && requestLists.size() >= Urls.PAGESIZE){
                    isLoading = true;
                    pageStart++;
                    getList();
                }
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
        refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(WebViewActivity.TITLE,title);
                intent.putExtra(WebViewActivity.URL,mLists.get(position-1).pageUrl);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
            }
        });
    }

    @Override
    protected void fillData() {
        super.fillData();
        refreshListView.setAdapter(adapter);
        isCreate = true;
        if(getUserVisibleHint()){
            isCreate= false;
            showLoadDialog(1);
            getList();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && isCreate){
            isCreate = false;
            showLoadDialog(1);
            getList();
        }
    }

    /** 获取新闻列表*/
    private void getList(){
        RequestParams params = new RequestParams(Urls.select_list);
        params.addQueryStringParameter("pageSize",Urls.PAGESIZE+"");
        params.addQueryStringParameter("pageStart",pageStart+"");
        params.addQueryStringParameter("channelId",channelId+"");
        getRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                finishHandler.sendEmptyMessageDelayed(0,200);
                try {
                    JSONArray array = new JSONArray(result.data);
                    JSONObject obj = array.getJSONObject(0);
                    Type type = new TypeToken<List<NewsItemBean>>(){}.getType();
                    requestLists = gson.fromJson(obj.optString("list"),type);
                    if(pageStart == 0){
                        mLists.clear();
                    }
                    if(requestLists.size() > 0){
                        refreshListView.setVisibility(View.VISIBLE);
                        llEmpty.setVisibility(View.GONE);
                        mLists.addAll(requestLists);
                        adapter.notifyDataSetChanged();
                    } else {

                        if(mLists.size() == 0){
                            llEmpty.setVisibility(View.VISIBLE);
                            refreshListView.setVisibility(View.GONE);
                        } else {
                            showToast("已全部加载");
                            llEmpty.setVisibility(View.GONE);
                            refreshListView.setVisibility(View.VISIBLE);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
    }

    private Handler finishHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshListView.onRefreshComplete();
        }
    };
}
